package com.tys.algorithm.advanced.code.class16;

//转化接口
public class GraphGenerator {

    // matrix 所有的边
    // N*3 的矩阵
    // [weight, from节点上面的值，to节点上面的值]
    //
    // [ 5 , 0 , 7]
    // [ 3 , 0,  1]
    //
    public static Graph createGraph(int[][] matrix) {
        Graph graph = new Graph();
        for (int i = 0; i < matrix.length; i++) {
            // 拿到每一条边， matrix[i]
            int weight = matrix[i][0]; //权重
            int from = matrix[i][1]; //起点
            int to = matrix[i][2]; //终点
            if (!graph.nodes.containsKey(from)) {
                //新建from点
                graph.nodes.put(from, new Node(from));
            }
            if (!graph.nodes.containsKey(to)) {
                //新建from点
                graph.nodes.put(to, new Node(to));
            }
            //得到from点
            Node fromNode = graph.nodes.get(from);
            //得到to点
            Node toNode = graph.nodes.get(to);
            //新建边
            Edge newEdge = new Edge(weight, fromNode, toNode);
            //from的直接邻居包含to：to加到from的nexts中
            fromNode.nexts.add(toNode);
            //from的出度加1
            fromNode.out++;
            //to的入度加1
            toNode.in++;
            //新边加到from的边集合
            fromNode.edges.add(newEdge);
            //新边加到to的边集合
            graph.edges.add(newEdge);
        }
        //返回图
        return graph;
    }

}
